package org.infosec.lc.exercises.ObjectNetworkTransmission.code.objectStream;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.ObjectOutputStream;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.net.SocketException;

import org.infosec.lc.exercises.ObjectNetworkTransmission.modle.IdentityCard;
import org.infosec.lc.exercises.ObjectNetworkTransmission.modle.Person;

/**
	文件名：ObjectStreamUDPSend.java
	作  者：林超
	时  间：2011-7-20下午01:34:38

	功能描述：构建ObjectOutputStream,并以UDP形式在网络中传输
	
	pom.xml	:
			
 */
public class ObjectStreamUDPSend {

	private DatagramSocket o_dgSock;
	private DatagramPacket o_dgPack;
	private ObjectOutputStream oos;
	private ByteArrayOutputStream baos;
	
	private Person person;
	
	{
		try {
			o_dgSock = new DatagramSocket();
		} catch (SocketException e) {
			e.printStackTrace();
		}
	}
	
	public void send(){
		check();
		try {
			//此处如不分配大小，默认32
//			baos = new ByteArrayOutputStream();
			baos = new ByteArrayOutputStream(1024);
			oos = new ObjectOutputStream(baos);
			
			oos.writeObject(person);
			oos.flush();
			
			sendUDP(baos.toByteArray());
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
	
	private void sendUDP(byte[] data){
		
		try {
			o_dgPack = new DatagramPacket(data,0,data.length);
			//得到本地IP
			o_dgPack.setAddress(InetAddress.getLocalHost());
//			o_dgPack.setAddress(InetAddress.getByName("ip"));
			o_dgPack.setPort(5000);
			
			o_dgSock.send(o_dgPack);
			o_dgSock.close();
			
			System.out.println("已发送ObjectStream成功");
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
	
	public ObjectStreamUDPSend(Person person) {
		this.person = person;
	}
	
	public ObjectStreamUDPSend(){
		super();
	}
	
	private void check(){
		if(o_dgSock==null){
			throw new NullPointerException("ObjectStreamUDPSend o_dgSock is null ");
		}
		if(person==null){
			throw new NullPointerException("ObjectStreamUDPSend person is null ");
		}
	}
	
	public static void main(String[] args) {
		IdentityCard cardId = new IdentityCard();
		cardId.setCardId(612321198611041734L);
		cardId.setAddress("我也不知道！");
		cardId.setBloodType("O型");
		
		Person person = new Person();
		person.setName("张三");
		person.setCardId(cardId);
		
		ObjectStreamUDPSend osUDP = new ObjectStreamUDPSend(person);
		osUDP.send();
		
	}
}

